<?php

namespace App\Livewire;

use App\Models\Benefit;
use Filament\Notifications\Notification;
use Illuminate\Database\Eloquent\Collection;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Attributes\On;
use Livewire\Component;

#[Layout('layouts.app')]
class MemberBenefit extends Component
{
    public Collection $benefits;

    private string $error = "操作失败";

    public function mount()
    {
        $this->benefits = Benefit::All();
    }
    public function render()
    {
        return view('livewire.member-benefit');
    }

    #[Computed]
    public function hasBenefit()
    {
        return auth('frontend')->user()->benefit()->get();
    }

    public function openBenefit($id)
    {
        if (!$this->benefitHandle($id)) {
            $this->errorNotice($this->error);
        } else {
            $this->successNotice('开通成功');
        }

    }

    private function benefitHandle($id) :bool
    {
        $benefit_info = Benefit::find($id);
        if (!$benefit_info) {
            $this->error = "权益不存在";
           return false;
        }
        $user = auth('frontend')->user();
        if ($user->benefit()->find($id)) {
            $this->error = "您已开通该权益";
            return false;
        }
        $user->benefit()->attach($id);
        return true;
    }

    #[On('success')]
    private function successNotice(string $message): Notification
    {
        return Notification::make()
            ->title($message)
            ->success()
            ->send();
    }
    #[On('error')]
    public function errorNotice(string $message): Notification
    {
        return Notification::make()
            ->title($message)
            ->danger()
            ->send();
    }
}
